<?php

namespace App\Http\Controllers;

use App\Http\Requests\Api\LoginRequest;
use App\Http\Requests\Api\WxLoginRequest;
use Illuminate\Http\Request;
use App\Http\Common\Consumer;
use App\Models\WxUser;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Overtrue\LaravelWeChat\Facade as EasyWechat;

class LoginController extends Controller
{
    /**
     * 微信授权登录
     * @param WxLoginRequest $request
     * @return mixed
     */
    public function wxLogin(WxLoginRequest $request)
    {
        $app = EasyWechat::officialAccount();
        $accessToken = $app->oauth
            ->getAccessToken($request->input('code'));
        $userInfo = $app->oauth->user($accessToken)->getOriginal();
        if(!isset($userInfo['unionid'])) {
            Log::error('系统未绑定开放平台，没有unionid');
            return $this->failed('请联系工作人员先绑定开放平台',4001);
        }

        // 保存授权用户信息
        $user = WxUser::query()->where('unionid', $userInfo['unionid'])->first();
        if (!$user) {
            $user = new WxUser($userInfo);
            $user->save();
        } else {
            $user->update($userInfo);
        }

        // 返回授权令牌
        $token = Auth::guard('api')->login($user);
        $data = [
            'token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::guard('admin')->factory()->getTTL() * 60,
            'user' => $user,
        ];

        return $this->success($data);
    }

    /**
     * 绑定手机号
     * @param LoginRequest $request
     * @return mixed
     */
    public function bindMobile(LoginRequest $request)
    {
        $cacheCode = Cache::get('phone_verification:' . $request->input('mobile'));
        if ($request->input('code') != $cacheCode) {
            return $this->failed('验证码错误', 403);
        }

        $user = Auth::guard('api')->user();
        $user->mobile = $request->input('mobile');
        $user->save();

        return $this->message('手机号绑定成功');
    }

    /**
     * 微信网页授权登录
     * string  code  Code参数
     *
     * @return string $en_res
     */
    public function wx_login(Request $request)
    {
        $Comsumer = new Consumer();
        $res = $request->all();

        if(!isset($res['code'])){
            return_value('缺少code参数',400);
        }
        $code = $res['code'];

        /*登录方式获取access_token*/
        $get_token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . $Comsumer->appid . '&secret=' . $Comsumer->secret . '&code=' . $code . '&grant_type=authorization_code';
        $access_token_str = curl_get($get_token_url);
        $access_token_list = json_decode($access_token_str, true);
        if (!isset($access_token_list['access_token'])) {
            return_value($access_token_list['errmsg'],$access_token_list['errcode']);
        }
        //access_token
        $access_token = $access_token_list['access_token'];
        //openid
        $openid = $access_token_list['openid'];
        //获取微信用户信息
        $get_user_info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $openid . '&lang=zh_CN';
        $user_msg_str = curl_get($get_user_info_url);
        $user_msg_list = json_decode($user_msg_str, true);
        //当用户信息获取为空时，不存session(修复刷新后不能获取到用户信息的BUG)
        if(!isset($user_msg_list['unionid'])){
            return_value('缺少unionid参数',401);
        }
        //unionid
        $unionId = $user_msg_list['unionid'];
        $WxUser = WxUser::where(array('unionid'=>$unionId))->select('token','token_at')->first();
        if (isset($WxUser)) {
            //查询token是否过期
            $token = $WxUser['token'];
            $token_at = $WxUser['token_at'];
            $over_token_at = strtotime($token_at) + $Comsumer->token_day * 24 * 3600;
            if($over_token_at < time()){
                //创建token
                $token = date('YmdHis').str_rand();
                WxUser::where(array('unionid'=>$unionId))->update(array('token' => $token,'token_at' => date('Y-m-d H:i:s'),'updated_at' => date('Y-m-d H:i:s')));
            }

            //更新用户信息
            $info['nickname'] = $user_msg_list['nickname'];
            $info['sex'] = $user_msg_list['sex'];
            $info['province'] = $user_msg_list['province'];
            $info['city'] = $user_msg_list['city'];
            $info['headimgurl'] = $user_msg_list['headimgurl'];
            $info['updated_at'] = date('Y-m-d H:i:s');
            WxUser::where(array('unionid'=>$unionId))->update($info);

            $data['token'] = $token;
        } else {
            //创建token
            $token = date('YmdHis').str_rand();
            $info['token'] = $token;
            $info['nickname'] = $user_msg_list['nickname'];
            $info['sex'] = $user_msg_list['sex'];
            $info['province'] = $user_msg_list['province'];
            $info['city'] = $user_msg_list['city'];
            $info['headimgurl'] = $user_msg_list['headimgurl'];
            $info['openid'] = $user_msg_list['openid'];
            $info['unionid'] = $user_msg_list['unionid'];
            $info['created_at'] = date('Y-m-d H:i:s');
            $info['updated_at'] = date('Y-m-d H:i:s');
            WxUser::insert($info);

            $data['token'] = $token;
        }

        return_value('成功',0,$data);
    }
}
